package com.xiaoyu.linkedArray;

/**
 * @program: DS_and_A
 * @description: 合并k个升序链表
 * 给你一个链表数组，每个链表都已经按升序排列。
 *
 * 请你将所有链表合并到一个升序链表中，返回合并后的链表。
 *
 * 示例 1：
 * 输入：lists = [[1,4,5],[1,3,4],[2,6]]
 * 输出：[1,1,2,3,4,4,5,6]
 * 解释：链表数组如下：
 * [
 *   1->4->5,
 *   1->3->4,
 *   2->6
 * ]
 * 将它们合并到一个有序链表中得到。
 * 1->1->2->3->4->4->5->6
 *
 * @author: YuWenYi
 * @create: 2021-06-02 09:36
 **/
public class MergeKLists_23 {

    //解法一:暴力合并!
    public ListNode mergeKLists1(ListNode[] lists) {
        if (lists==null || lists.length == 0) return null;
        if (lists.length == 1) return lists[0];

        ListNode res = merge(lists[0], lists[1]);

        for (int i = 2; i < lists.length; i++) {
            res = merge(res, lists[i]);
        }
        return res;
    }

    public ListNode merge(ListNode node1,ListNode node2){
        ListNode dummy = new ListNode(0);
        ListNode p = dummy;
        while (node1 != null && node2 != null){
            if (node1.val < node2.val){
                p.next = node1;
                node1 = node1.next;
            }else {
                p.next = node2;
                node2 = node2.next;
            }
            p = p.next;
        }
        p.next = node1 != null ? node1 : node2;

        return dummy.next;
    }

    //解法二:使用分治法去进行归并
    public ListNode mergeKLists(ListNode[] lists) {
        return cut(lists, 0, lists.length-1);
    }

    public ListNode cut(ListNode[] lists,int start,int tail) {
        if (start == tail) return lists[start];
        if (start > tail) return null;
        int mid = (start+tail) >> 1;
        ListNode node1 = cut(lists, start, mid);
        ListNode node2 = cut(lists, mid + 1, tail);

        return merge(node1,node2);
    }

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1,new ListNode(2,new ListNode(4)));
        ListNode l2 = new ListNode(3,new ListNode(5,new ListNode(7)));
        ListNode l3 = new ListNode(6,new ListNode(8,new ListNode(10)));

        ListNode[] lists = {l1,l2,l3};
        MergeKLists_23 mergeKLists23 = new MergeKLists_23();
        ListNode listNode = mergeKLists23.mergeKLists(lists);
        ListNode.printList(listNode);
    }
}
